const express = require('express')
const router = express.Router();
const fs = require('fs')
const userList = require('../mock/user.json')
const list = require('../mock/list.json')


function resModel(code, msg) {
  return {
    code,
    msg
  }
}

// const successModel = {
//   code: 0,
//   msg: 'success',
// }
// const failModel = {
//   code: -1,
//   msg: 'fail',
// }

// denglu
router.post('/login', (req, res, next) => {
  const { phone, pwd } = req.body
  let flag = userList.some(val => val.phone === phone && val.pwd === pwd)
  console.log(flag, 'flag')
  if (flag) {
    res.send(resModel(0, '登陆成功'))
  } else {
    res.send(resModel(-1, '登陆失败'))
  }
})

// zhuce
router.post('/register', (req, res, next) => {
  const { phone, pwd } = req.body
  let flag = userList.some(val => val.phone === phone)
  if (flag) {
    res.send(resModel(-1, '已经存在，请重新注册'))
  } else {
    userList.push(req.body);
    fs.writeFileSync('./mock/user.json', JSON.stringify(userList))
    res.send(resModel(0, '注册成功'))
  }
})

router.post('/add', (req, res, next) => {
  // req.body;
  let id = list.length;
  list.push({ id, ...req.body })
  fs.writeFileSync('./mock/list.json', JSON.stringify(list))
  res.send({ id: id, ...resModel(0, '添加成功') })
})

// 分页
router.get('/page', (req, res, next) => {
  const { page, size } = req.query;
  let list = JSON.parse(fs.readFileSync('./mock/list.json').toString())
  console.log(list, 'list')
  res.send({
    ...resModel(0, '查询成功'),
    data: list.filter((v, index) => index >= page * size && index < (page * 1 + 1) * size)
  })
})

// 列表接口
router.get('/list', (req, res, next) => {
  res.send({
    ...resModel(0, '查询成功'),
    data: list
  })
})

// 删除数据
router.get('/delete', (req, res, next) => {
  const { id } = req.query;
  let deleteData = list.filter(val => val.id != id)
  fs.writeFileSync('./mock/list.json', JSON.stringify(deleteData))
  res.send({
    ...resModel(0, '删除成功'),
    data: deleteData
  })
})


module.exports = router;